<?php
/**
 * Product_Controller
 * - Controller for module page Home
 * @author ANHTAM
 * @since 1.1 - Sep 27, 2011
 * $Id: $
 */
// Require module for controller
require_once(LIB_UI_DIR . "/NganLuong.class.php");
require_once(LIB_UI_DIR . "/BaoKim.class.php");
class Product_Controller extends Controller {
	/**
     * - Constructor
     */
    public function __construct() {
    	parent::__construct();
    	$this->errorArr = array();
    }
    
    /**
     * actionIndex
     * - page index of controller
     */
    public function actionIndex() {
    	
    	// Process init
        $objView = new View ();
        $this->tpl_title = '.::MUA THE NHANH::.';
        
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
     * actionDetail
     * - page detail of controller
     */
    public function actionDetail() {
    	
    	// Process init
        $objView = new View ();
        $this->tpl_title = '.::CHI TIẾT SẢN PHẨM::.';
        Session::Set('MUA', '1');
        $this->arrSanPham = array();
        $this->name = '';
        $this->CHKH = array();
        
        $ojbCate = new SanphamCategory();
        $ojbSCate = new SanphamSCategory();
        $ojbKhoHang = new KhoHang();
        $ojbSanPham = new MSanpham();
        
        $getGet = FunctionCommon::getGet(array('id', 'danhmucid', 'iddm', 'subiddm', 'checked'));
        $this->id = $getGet['id'];
        $this->danhmucid = ($getGet['danhmucid'] == 0) ? '' : $getGet['danhmucid'];
        $this->iddm = ($getGet['iddm'] == 0) ? '' : $getGet['iddm'];
        $this->subiddm = ($getGet['subiddm'] == 0) ? '' : $getGet['subiddm'];
        
        if ($this->iddm != '' && $this->subiddm != '') {
        	$keySCatego = $ojbSCate->getByPrimaryKey($this->subiddm);
        	$this->name = $keySCatego['name'];
	        $arrSanPham = $ojbSanPham->getAllByAttribute(array('danhmuc_id'=>array('value'=>$this->danhmucid, 'math'=>'='), 'iddm'=>array('value'=>$this->iddm,'math'=>'='), 'iddmc'=>array('value'=>$this->subiddm,'math'=>'=')), array('id','name', 'code', 'gia1', 'gia2', 'check_km', 'soluong'));
	        if (count ($arrSanPham) > 0) {
	        	if ($this->danhmucid > 1) {
	        		$this->arrSanPham = $arrSanPham;
	        	} else {
			        foreach ($arrSanPham as $sp) {
			        	$sp['soluong'] = $ojbKhoHang->totalSanPham($sp['id']);
			        	$this->arrSanPham[] = $sp;
			        }
	        	}
	        }
        }
        
    	if ($this->iddm != '' && $this->subiddm == '') {
    		$keyCatego = $ojbCate->getByPrimaryKey($this->iddm);
        	$this->name = $keyCatego['name'];
	        $arrSanPham = $ojbSanPham->getAllByAttribute(array('danhmuc_id'=>array('value'=>$this->danhmucid, 'math'=>'='), 'iddm'=>array('value'=>$this->iddm,'math'=>'='), 'iddmc'=>array('value'=>$this->subiddm,'math'=>'=')), array('id','name', 'code', 'gia1', 'gia2', 'check_km', 'soluong'));
	        if (count ($arrSanPham) > 0) {
	        	if ($this->danhmucid > 1) {
	        		$this->arrSanPham = $arrSanPham;
	        	} else {
			        foreach ($arrSanPham as $sp) {
			        	$sp['soluong'] = $ojbKhoHang->totalSanPham($sp['id']);
			        	$this->arrSanPham[] = $sp;
			        }
	        	}
	        }
        }
        
        if ($this->subiddm != '') {
        	$this->CHKH = $ojbSCate->getOneByAttr(array('id'=>$this->subiddm), array('chitiet', 'huongdan', 'khuyenmai', 'hotro'));
        }
        
        //echo "<pre>";print_r($this->arrSanPham);exit;
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
     * actionGioHang
     * - page giohang of controller
     */
    public function actionGioHang() {
    	
    	// Process init
        $objView = new View ();
        $this->tpl_title = '.::CHI TIẾT GIỎ HÀNG::.';
        $this->erID = '';
        
    	if (!$this->loginFlag) {
        	FunctionCommon::sendRedirect('account/error-login#content');
        }
        
        $dataGet = FunctionCommon::getGet(array('id', 'danhmucid', 'iddm', 'subiddm', 'er'));
        $this->id = $dataGet['id'];
        $this->danhmucid = ($dataGet['danhmucid'] == 0) ? '' : $dataGet['danhmucid'];
        $this->iddm = ($dataGet['iddm'] == 0) ? '' : $dataGet['iddm'];
        $this->subiddm = ($dataGet['subiddm'] == 0) ? '' : $dataGet['subiddm'];
        
        if ($dataGet['er'] != '' && $dataGet['er'] != 'tt') {
        	$this->errorArr[$dataGet['er']] = 'Số lượng ko đủ, bạn vui lòng cập nhật lại';
        	$this->erID = $dataGet['er'];
        }
        if ($dataGet['er'] != '' && $dataGet['er'] == 'tt') {
        	$this->errorArr['tt'] = 'Thanh toán ko thành công';
        }
        
        $dataPost = FunctionCommon::getPost(array('mode'));

        $ojbGioHang = new GioHang();
        $ojbSanPham = new MSanpham();
        if ($this->id != '' && Session::Get('MUA') == '1' && $dataPost['mode'] == '') {
	        $arrSanPham = $ojbSanPham->getByPrimaryKey($this->id);

	        // Update gio Hang
	        if ($ojbGioHang->checkIssetGioHang($this->dataUser['id'], $this->id)) {
	        	$ojbGioHang->updateSoLuong($this->dataUser['id'], $this->id, 0, 1, ($arrSanPham['check_km']==1) ? $arrSanPham['gia2'] : $arrSanPham['gia1']);
	        } else {
	        	$ojbGioHang->setAttribute('gh_user', $this->dataUser['id']);
	        	$ojbGioHang->setAttribute('gh_sanpham', $this->id);
	        	$ojbGioHang->setAttribute('soluong', '1');
	        	$ojbGioHang->setAttribute('dongia', ($arrSanPham['check_km']==1) ? $arrSanPham['gia2'] : $arrSanPham['gia1']);
	        	$ojbGioHang->setAttribute('tongtien', ($arrSanPham['check_km']==1) ? $arrSanPham['gia2'] : $arrSanPham['gia1']);
	        	$ojbGioHang->setAttribute('tensanpham', $arrSanPham['name']);
	        	$ojbGioHang->setAttribute('code', $arrSanPham['code']);
	        	$ojbGioHang->setAttribute('type', ($arrSanPham['danhmuc_id'] > 1) ? '2' : '1');
			    $ojbGioHang->setAttribute('insert_at', date('Y-m-d H:i:s'));
			    $ojbGioHang->insert();
	        }
	        $ojbGioHang->emptyAttribute();   	  	
        }
        if ($dataPost['mode'] == 'capnhat' && $this->id != '') {
        	$capNhatSoLuong = 'capnhatsoluong_' . $this->id;
        	$donGia = 'donGia_' . $this->id;
        	$postCapnhat = FunctionCommon::getPost(array($capNhatSoLuong, $donGia));
        	if (!Validator::isIntegerPositive($postCapnhat[$capNhatSoLuong])) {
        		$this->errorArr[$capNhatSoLuong] = 'Bạn vui lòng nhập số lượng kiểu số';
        	}
        	
			// Lay thong tin tu gio hang
        	$getSoLuongByGioHangID = $ojbGioHang->getOneByAttr(array('id' => $this->id), array('id', 'gh_sanpham', 'type'));
        	// Lay thong tin tu san pham
        	$ojbKhoHang = new KhoHang();
        	if ($getSoLuongByGioHangID['type'] == '1') {
        		$getSoLuongFromKhoHang= $ojbKhoHang->totalSanPham($getSoLuongByGioHangID['gh_sanpham']);
        	} else {
        		$getSoLuongFromKhoHang = $ojbKhoHang->totalSanPham($getSoLuongByGioHangID['gh_sanpham'], true);
        	}
        	
        	// Kiem tra so luong san pham co du ko
        	if ($postCapnhat[$capNhatSoLuong] > $getSoLuongFromKhoHang) {
        		$this->errorArr[$capNhatSoLuong] = 'Bạn chỉ được nhập tối đa ' . $getSoLuongFromKhoHang . ' sản phẩm này !';
        	}
        	
        	if (count($this->errorArr) == 0) {
        		// Cap nhat gio hang
        		$ojbGioHang->setAttribute('soluong', $postCapnhat[$capNhatSoLuong]);
        		$ojbGioHang->setAttribute('tongtien', ($postCapnhat[$donGia] * $postCapnhat[$capNhatSoLuong]));
        		$ojbGioHang->update(array('id' => $this->id));
        		$ojbGioHang->emptyAttribute();
        	}
        }
        
        if ($dataPost['mode'] == 'delete' && $this->id != '') {
        	// Update gio hang
        	$ojbGioHang->setAttribute('del', '1');
        	$ojbGioHang->update(array('id'=>$this->id));
        	$ojbGioHang->emptyAttribute();
        }
        Session::Set('MUA', '2');
        $this->gioHangYour = $ojbGioHang->getGioHangYour($this->dataUser['id']);
        
        $field = "d.name as nameD, c.name as nameC, s.name as nameS, s.code, gh.id, gh.soluong, gh.dongia, gh.tongtien, gh.active, gh.maHang, gh.insert_at";
        $atrr = array('gh.gh_user'=>array('value'=>$this->dataUser['id'],'math'=>'='), 'gh.del'=>array('value'=>0,'math'=>'='), 'gh.active'=>array('value'=>0,'math'=>'='));
        $this->spGioHang = $ojbGioHang->getThongTinSPGioHang($atrr, $field, 'gh.insert_at');
        
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
     * actionPtThanhToan
     * - page ptthanhtoan of controller
     */
    public function actionPtThanhToan() {
    	
    	// Process init
        $objView = new View ();
        $this->tpl_title = '.::PHƯƠNG THỨC THANH TOÁN::.';
        
    	if (!$this->loginFlag) {
        	FunctionCommon::sendRedirect('account/error-login#content');
        }
        
        if (isset($_GET['er']) && $_GET['er'] == 1) {
        	$this->errorArr['thanhtoan_1'] = 'Bạn vui lòng chọn 1 phương thức thanh toán';
        }
        Session::Set('MUA', '3');
        
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
     * actionThanhToan
     * - page thanhtoan of controller
     */
    public function actionThanhToan() {
    	
    	// Process init
        $objView = new View ();
        $this->tpl_title = '.::THANH TOÁN::.';
        $this->spGioHang = array();
        $this->phiDV = 0;
        $this->thanhtoan = false;
        $this->maHang = '';
        $idSanPhamKhoHang = '';
        $idSanPhamNull = '';
        $this->activeFlag = false;
        
    	if (!$this->loginFlag) {
        	FunctionCommon::sendRedirect('account/error-login#content');
        }
        
        $this->getPost = FunctionCommon::getPost(array('thanhtoan', 'mode', 'totalThanhToan'));
        $this->dataGet = FunctionCommon::getGet(array('result'));

        if ($this->getPost['thanhtoan'] == '') {
        	FunctionCommon::sendRedirect('product/error-thanh-toan#content');
        } else {
        	$ojbGioHang = new GioHang();
        	$ojbKhoHang = new KhoHang();
        	
        	//$field = array('id', 'gh_sanpham', 'soluong', 'dongia', 'tongtien', 'active', 'tensanpham', 'code', 'maHang', 'insert_at');
        	//$this->spGioHang = $ojbGioHang->getAllByAttribute(array('gh_user'=>array('value'=>$this->dataUser['id'],'math'=>'='), 'del'=>array('value'=>'0','math'=>'='), 'active'=>array('value'=>'0','math'=>'=')), $field, array(), 'insert_at');
        	$field = "d.name as nameD, c.name as nameC, s.name as nameS, s.code, gh.id, gh.gh_sanpham, gh.soluong, gh.dongia, gh.tongtien, gh.active, gh.maHang, gh.type, gh.insert_at";
        	$atrr = array('gh.gh_user'=>array('value'=>$this->dataUser['id'],'math'=>'='), 'gh.del'=>array('value'=>0,'math'=>'='), 'gh.active'=>array('value'=>0,'math'=>'='));
        	$this->spGioHang = $ojbGioHang->getThongTinSPGioHang($atrr, $field, 'gh.insert_at');
        
        	foreach ($this->spGioHang as $check) {
        		if ($check['type'] == '1') {
        			if ($ojbKhoHang->totalSanPham($check['gh_sanpham']) < $check['soluong']) {
        				FunctionCommon::sendRedirect('product/error-gio-hang-capnhatsoluong_'. $check['id'] .'#content');
        			} else {
	        			// Get from Kho Hang
		        		$khoHangIDA = $ojbKhoHang->getAllByAttribute(array('sanpham_id'=>array('value'=>$check['gh_sanpham'],'math'=>'='), 'del'=>array('value'=>'0','math'=>'=')), array('id'), array(0, $check['soluong']), 'insert_at');
		        		if (count ($khoHangIDA) > 0) {
		        			foreach ($khoHangIDA as $IDKH) {
		        				$idSanPhamKhoHang .= $IDKH['id'] . "-";
		        			}
		        		}
        			}
        		} else {
        			if ($ojbKhoHang->totalSanPham($check['gh_sanpham'], true) < $check['soluong']) {
        				FunctionCommon::sendRedirect('product/error-gio-hang-capnhatsoluong_'. $check['id'] .'#content');
        			} else {
        				$idSanPhamNull .= $check['gh_sanpham'] . "_";
        			}
        		}
        	}
        	
        	if ($this->getPost['mode'] == 'thanhtoan' && Session::Get('MUA') == '3' && count ($this->errorArr) == 0) {
        		// Tao ma hoa don        		
        		$this->maHang = date('Ymd').'-'.date('His');
        		
        		if ($this->getPost['thanhtoan'] == '2') { // Type thanh toan bang tien mat
        			Session::Set('MUA', '4');
        			$arInformation = array('maHang' => $this->maHang,
        								   'id_khohang' => $idSanPhamKhoHang,
        								   'id_sanpham' => $idSanPhamNull,
        								   'phiDV' => $this->phiDV,
        								   'type_tt' => $this->getPost['thanhtoan']);
        			Session::Set("GIOHANGUSER", $this->spGioHang);
        			Session::Set("INFORMATION", $arInformation);
        			FunctionCommon::sendRedirect("product/ket-thuc-thanh-toan#content");
        		} elseif ($this->getPost['thanhtoan'] == '3') { // Type thanh toan qua Ngan Luong
        			Session::Set('MUA', '4');
        			$arInformation = array('maHang' => $this->maHang,
        								   'id_khohang' => $idSanPhamKhoHang,
        								   'id_sanpham' => $idSanPhamNull,
        								   'phiDV' => $this->phiDV,
        								   'type_tt' => $this->getPost['thanhtoan']);
        			Session::Set("GIOHANGUSER", $this->spGioHang);
        			Session::Set("INFORMATION", $arInformation);
        			
        			//Khai báo url trả về 
					$return_url = WEB_LINK . "/product/ket-thuc-thanh-toan";
        			//Tài khoản nhận tiền
					$receiver = "phuminhly@gmail.com";
					//Thông tin giao dịch
					$transaction_info = "Hãy lập trình thông tin giao dịch của bạn vào đây";
					//Mã giỏ hàng 
					$order_code = $this->maHang;
					//Giá của cả giỏ hàng 
					$price = str_replace(",", "", $this->getPost['totalThanhToan']);
				    //Khai báo đối tượng của lớp NL_Checkout
					$NganLuong = new NganLuong();
					//Tạo link thanh toán đến nganluong.vn
					FunctionCommon::sendRedirect($NganLuong->buildCheckoutUrl($return_url, $receiver, $transaction_info, $order_code, $price), false);
        		} elseif ($this->getPost['thanhtoan'] == '4') { // Type thanh toan qua Bao Kim
        			Session::Set('MUA', '4');
        			$arInformation = array('maHang' => $this->maHang,
        								   'id_khohang' => $idSanPhamKhoHang,
        								   'id_sanpham' => $idSanPhamNull,
        								   'phiDV' => $this->phiDV,
        								   'type_tt' => $this->getPost['thanhtoan']);
        			Session::Set("GIOHANGUSER", $this->spGioHang);
        			Session::Set("INFORMATION", $arInformation);
        			
        			
        			// Mã đơn hàng
        			$order_id = $this->maHang;
        			// Email tài khoản người bán
        			$business = "lyminhphu@yahoo.com.vn";
        			// Giá trị đơn hàng
        			$total_amount = str_replace(",", "", $this->getPost['totalThanhToan']);
        			// Phí vận chuyển
        			$shipping_fee = 0;
        			// Thuế
        			$tax_fee = 0;
        			// Mô tả đơn hàng
        			$order_description = "Hãy lập trình thông tin giao dịch của bạn vào đây";
        			// Url trả về khi thanh toán thành công
        			$url_success = WEB_LINK . "/product/ket-thuc-thanh-toan";
        			// Url trả về khi hủy thanh toán
        			$url_cancel = WEB_LINK . "/product/gio-hang";
        			// Url chi tiết đơn hàng
        			$url_detail = WEB_LINK . "/product/phuong-thuc-thanh-toan";
				    //Khai báo đối tượng của lớp NL_Checkout
					$BaoKim = new BaoKim();
					//Tạo link thanh toán đến nganluong.vn
					FunctionCommon::sendRedirect($BaoKim->createRequestUrl($order_id, $business, $total_amount, $shipping_fee, $tax_fee, $order_description, $url_success, $url_cancel, $url_detail), false);
        		}
        	}
        }
        
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
     * action
     * - page complete of controller
     */
    public function actionComplete() {
    	
    	// Process init
        $objView = new View ();
        $this->tpl_title = '.::HOÀN THÀNH::.';
        $this->spGioHang = array();
        $this->maHang = '';
        $this->phiDV = '';
        $this->type_tt = '';
        $id_khohang = '';
        $id_sanpham = '';
        $this->flagActive = false;
        $this->arMaTheActive = array();
        $this->arSanPhamActive = array();
        
    	if (!$this->loginFlag) {
        	FunctionCommon::sendRedirect('account/error-login#content');
        }
        $GIOHANGUSER = Session::Get("GIOHANGUSER");
        $INFORMATION = Session::Get("INFORMATION");
        
        if (is_array($GIOHANGUSER) && !empty($GIOHANGUSER)) {
        	$this->spGioHang = $GIOHANGUSER;
        } else {
        	Session::Remove("GIOHANGUSER");
        	Session::Remove("INFORMATION");
        	FunctionCommon::sendRedirect("product/gio-hang#content");
        }

        if (is_array($INFORMATION) && !empty($INFORMATION)) {
        	$this->maHang = $INFORMATION['maHang'];
        	$id_khohang = $INFORMATION['id_khohang'];
        	$id_sanpham = $INFORMATION['id_sanpham'];
        	$this->phiDV = $INFORMATION['phiDV'];
        	$this->type_tt = $INFORMATION['type_tt'];
        } else {
        	Session::Remove("GIOHANGUSER");
        	Session::Remove("INFORMATION");
        	FunctionCommon::sendRedirect("product/gio-hang#content");
        }
        
        require_once(LIB_DAO_DIR . "/DonHang.class.php");
        $ojbSanPham = new MSanpham();
        $ojbGioHang = new GioHang();
        $ojbKhoHang = new KhoHang();
        
        if ($this->type_tt == '2') {
        	// Insert vao hoa don
	        $ojbDonHang = new DonHang();
	        $ojbDonHang->setAttribute('maHang', $this->maHang);
	        $ojbDonHang->setAttribute('id_khohang', $id_khohang);
	        $ojbDonHang->setAttribute('id_sanpham', $id_sanpham);
	        $ojbDonHang->setAttribute('phiDV', $this->phiDV);
	      	$ojbDonHang->setAttribute('type_tt', $this->type_tt);
	      	$ojbDonHang->setAttribute('user_id', $this->dataUser['id']);
		    $ojbDonHang->setAttribute('insert_at', date('Y-m-d H:i:s'));
		    $ojbDonHang->insert();
		    // Update gio hang
		    foreach ($this->spGioHang as $ghs) {
		    	$ojbGioHang->setAttribute('active', '1');
		    	$ojbGioHang->setAttribute('maHang', $this->maHang);
		    	$ojbGioHang->update(array('id' => $ghs['id']));
		    	$ojbGioHang->emptyAttribute();
		    }
		    $this->gioHangYour = array();
		    // Send mail toi khach hang
		    $this->resultSend($this->spGioHang, $this->maHang, $this->phiDV);
		    Session::Remove("GIOHANGUSER");
        	Session::Remove("INFORMATION");
        } elseif ($this->type_tt == '3') {
        	//Lấy thông tin giao dịch
			$transaction_info=$_GET["transaction_info"];
			//Lấy mã đơn hàng 
			$order_code=$_GET["order_code"];
			//Lấy tổng số tiền thanh toán tại ngân lượng 
			$price=$_GET["price"];
			//Lấy mã giao dịch thanh toán tại ngân lượng
			$payment_id=$_GET["payment_id"];
			//Lấy loại giao dịch tại ngân lượng (1=thanh toán ngay ,2=thanh toán tạm giữ)
			$payment_type=$_GET["payment_type"];
			//Lấy thông tin chi tiết về lỗi trong quá trình giao dịch
			$error_text=$_GET["error_text"];
			//Lấy mã kiểm tra tính hợp lệ của đầu vào 
			$secure_code=$_GET["secure_code"];
			$NganLuong = new NganLuong();
			$check = $NganLuong->verifyPaymentUrl($transaction_info, $order_code, $price, $payment_id, $payment_type, $error_text, $secure_code);
			if ($check) {
	        	// Insert vao hoa don
		    	$ojbDonHang = new DonHang();
	   			$ojbDonHang->setAttribute('maHang', $this->maHang);
	   			$ojbDonHang->setAttribute('id_khohang', $id_khohang);
	   			$ojbDonHang->setAttribute('id_sanpham', $id_sanpham);
	      		$ojbDonHang->setAttribute('phiDV', $this->phiDV);
	        	$ojbDonHang->setAttribute('type_tt', $this->type_tt);
	        	$ojbDonHang->setAttribute('user_id', $this->dataUser['id']);
	        	$ojbDonHang->setAttribute('active', '1');
		    	$ojbDonHang->setAttribute('insert_at', date('Y-m-d H:i:s'));
		    	$ojbDonHang->insert();
				// Update gio hang
				$arrSPTypeBy2 = array();
				foreach ($this->spGioHang as $ghs) {
				    $ojbGioHang->setAttribute('active', '1');
				    $ojbGioHang->setAttribute('maHang', $this->maHang);
				    $ojbGioHang->update(array('id' => $ghs['id']));
				    $ojbGioHang->emptyAttribute();
				    if ($ghs['type'] == '2') {
				    	$arrSPTypeBy2[$ghs['gh_sanpham']] = $ghs['soluong'];
				    }
				}
				// Update kho hang
				$idKhoHang = explode("-", $id_khohang);
				if (is_array($idKhoHang) && !empty($idKhoHang)) {
					// Get thong tin ma the
	        		$field = "d.name as nameD, c.name as nameC, s.name as nameS, kh.seri, kh.maSanPham";
			   		foreach ($idKhoHang as $idKH) {
			     		if ($idKH != '') {
			     			$conf = array('kh.id' => array('math'=>'=', 'value'=>$idKH));
			     			$this->arMaTheActive[] = $ojbKhoHang->getInformationCard($conf, $field);
			        		$ojbKhoHang->setAttribute("del", "1");
			        		$ojbKhoHang->update(array("id" => $idKH));
			        		$ojbKhoHang->emptyAttribute();
			      		}
			     	}
			   	}
			   	// Update san pham
			   	$idSanPham = explode("-", $id_sanpham);
			   	if (is_array($idSanPham) && !empty($idSanPham) && count($arrSPTypeBy2) > 0) {
			   		$field = "d.name as nameD, c.name as nameC, s.name as nameS";
			   		foreach ($idSanPham as $idSP) {
			   			if ($idSP != '') {
			   				$conf = array('s.id' => array('math'=>'=', 'value'=>$idSP));
			   				$arrSP = $ojbSanPham->sanPhamHome($conf, $field, 's.seq');
			   				$this->arSanPhamActive[] = $arrSP[0];
			   				$ojbSanPham->updateSoLuong($idSP, $arrSPTypeBy2[$idSP]);
			   			}
			   		}
			   	}
			   	$this->flagActive = true;
			   	$this->gioHangYour = array();
				// Send mail toi khach hang
				$this->resultSend($this->spGioHang, $this->maHang, $this->phiDV);
				Session::Remove("GIOHANGUSER");
	        	Session::Remove("INFORMATION");
			} else {
				FunctionCommon::sendRedirect("product/error-gio-hang-tt#content");
			}
    	} elseif ($this->type_tt == '4') {
    		$baoKim = new BaoKim();
    		$check = $baoKim->verifyResponseUrl($_GET);
    		if ($check) {
    			// Insert vao hoa don
		    	$ojbDonHang = new DonHang();
	   			$ojbDonHang->setAttribute('maHang', $this->maHang);
	   			$ojbDonHang->setAttribute('id_khohang', $id_khohang);
	   			$ojbDonHang->setAttribute('id_sanpham', $id_sanpham);
	      		$ojbDonHang->setAttribute('phiDV', $this->phiDV);
	        	$ojbDonHang->setAttribute('type_tt', $this->type_tt);
	        	$ojbDonHang->setAttribute('user_id', $this->dataUser['id']);
	        	$ojbDonHang->setAttribute('active', '1');
		    	$ojbDonHang->setAttribute('insert_at', date('Y-m-d H:i:s'));
		    	$ojbDonHang->insert();
				// Update gio hang
				$arrSPTypeBy2 = array();
				foreach ($this->spGioHang as $ghs) {
				    $ojbGioHang->setAttribute('active', '1');
				    $ojbGioHang->setAttribute('maHang', $this->maHang);
				    $ojbGioHang->update(array('id' => $ghs['id']));
				    $ojbGioHang->emptyAttribute();
				    if ($ghs['type'] == '2') {
				    	$arrSPTypeBy2[$ghs['gh_sanpham']] = $ghs['soluong'];
				    }
				}
				// Update kho hang
				$idKhoHang = explode("-", $id_khohang);
				if (is_array($idKhoHang) && !empty($idKhoHang)) {
					// Get thong tin ma the
	        		$field = "d.name as nameD, c.name as nameC, s.name as nameS, kh.seri, kh.maSanPham";
			   		foreach ($idKhoHang as $idKH) {
			     		if ($idKH != '') {
			     			$conf = array('kh.id' => array('math'=>'=', 'value'=>$idKH));
			     			$this->arMaTheActive[] = $ojbKhoHang->getInformationCard($conf, $field);
			        		$ojbKhoHang->setAttribute("del", "1");
			        		$ojbKhoHang->update(array("id" => $idKH));
			        		$ojbKhoHang->emptyAttribute();
			      		}
			     	}
			   	}
			   	// Update san pham
			   	$idSanPham = explode("-", $id_sanpham);
			   	if (is_array($idSanPham) && !empty($idSanPham) && count($arrSPTypeBy2) > 0) {
			   		$field = "d.name as nameD, c.name as nameC, s.name as nameS";
			   		foreach ($idSanPham as $idSP) {
			   			if ($idSP != '') {
			   				$conf = array('s.id' => array('math'=>'=', 'value'=>$idSP));
			   				$arrSP = $ojbSanPham->sanPhamHome($conf, $field, 's.seq');
			   				$this->arSanPhamActive[] = $arrSP[0];
			   				$ojbSanPham->updateSoLuong($idSP, $arrSPTypeBy2[$idSP]);
			   			}
			   		}
			   	}
			   	$this->flagActive = true;
			   	$this->gioHangYour = array();
				// Send mail toi khach hang
				$this->resultSend($this->spGioHang, $this->maHang, $this->phiDV);
				Session::Remove("GIOHANGUSER");
	        	Session::Remove("INFORMATION");
    		} else {
    			FunctionCommon::sendRedirect("product/error-gio-hang-tt#content");
    		}
    	} else {
    		FunctionCommon::sendRedirect("product/gio-hang#content");
    	}
		
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
     * actionDonHang
     * - page donhang of controller
     */
    public function actionDonHang() {
    	
    	// Process init
        $objView = new View ();
        $this->tpl_title = '.::ĐƠN HÀNG::.';
        $this->spGioHang = array();
        $this->detailDH = false;
        $this->congThanhToan = '';
        $this->arMaTheActive = array();
        $this->arSanPhamActive = array();
        $this->activeFlag = false;
        
    	if (!$this->loginFlag) {
        	FunctionCommon::sendRedirect('account/error-login#content');
        }
        
        $this->getGet = FunctionCommon::getGet(array('code'));
        
        require_once(LIB_DAO_DIR . "/DonHang.class.php");
        $ojbCate = new SanphamCategory();
        $ojbSCate = new SanphamSCategory();
        $ojbSanPham = new MSanpham();
        $ojbDonHang = new DonHang();
        $ojbKhoHang = new KhoHang();
        $this->spDonHang = $ojbDonHang->getAllByAttribute(array('user_id '=>array('value'=>$this->dataUser['id'], 'math'=>'=')), array(), array(), 'insert_at');
        
        if ($this->getGet['code'] != '') {
        	$ojbGioHang = new GioHang();
        	//$field = array('id', 'gh_sanpham', 'soluong', 'dongia', 'tongtien', 'active', 'tensanpham', 'code', 'maHang', 'insert_at');
        	//$this->spGioHang = $ojbGioHang->getAllByAttribute(array('maHang' => array('value' => $this->getGet['code'], 'math' => '='), 'active' => array('value' => '1', 'math' => '=')), $field, array(), 'insert_at');
        	$field = "d.name as nameD, c.name as nameC, s.name as nameS, s.code, gh.id, gh.gh_sanpham, gh.soluong, gh.dongia, gh.tongtien, gh.active, gh.maHang, gh.insert_at";
        	$atrr = array('gh.maHang'=>array('value'=>$this->getGet['code'],'math'=>'='), 'gh.active'=>array('value'=>1,'math'=>'='));
        	$this->spGioHang = $ojbGioHang->getThongTinSPGioHang($atrr, $field, 'gh.insert_at');
        	
        	// Get cong thanh toan
        	$this->congThanhToan = $ojbDonHang->getOneByAttr(array('maHang' => $this->getGet['code']), array('id_khohang', 'id_sanpham', 'type_tt', 'phiDV', 'active'));
        	if ($this->congThanhToan['active'] == '1') {
        		$this->activeFlag = true;
				$idKhoHang = explode("-", $this->congThanhToan['id_khohang']);
				if (is_array($idKhoHang) && !empty($idKhoHang)) {
					// Get thong tin ma the
	        		$field = "d.name as nameD, c.name as nameC, s.name as nameS, kh.seri, kh.maSanPham";
			   		foreach ($idKhoHang as $idKH) {
			     		if ($idKH != '') {
			     			$conf = array('kh.id' => array('math'=>'=', 'value'=>$idKH));
			     			$this->arMaTheActive[] = $ojbKhoHang->getInformationCard($conf, $field);
			      		}
			     	}
			   	}
			   	
			   	$idSanPham = explode("-", $this->congThanhToan['id_sanpham']);
			   	if (is_array($idSanPham) && !empty($idSanPham)) {
			   		$field = "d.name as nameD, c.name as nameC, s.name as nameS";
			   		foreach ($idSanPham as $idSP) {
			   			if ($idSP != '') {
			   				$conf = array('s.id' => array('math'=>'=', 'value'=>$idSP));
			   				$arrSP = $ojbSanPham->sanPhamHome($conf, $field, 's.seq');
			   				$this->arSanPhamActive[] = $arrSP[0];
			   			}
			   		}
			   	}
        	}
        	$this->detailDH = true;
        }
        //echo "<pre>";print_r($this->arMaTheActive);
        //echo "<pre>";print_r($this->arSanPhamActive);exit;
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
     * actionHistory
     * - page thanhtoan of controller
     */
    public function actionHistory() {
    	
    	// Process init
        $objView = new View ();
        $this->tpl_title = '.::LỊCH SỬ MUA HÀNG::.';
        
    	if (!$this->loginFlag) {
        	FunctionCommon::sendRedirect('account/error-login#content');
        }
        require_once(LIB_CORE_DIR . "/Paging.class.php");       
        $ojbGioHang = new GioHang();
        
    	// List all
    	$arrParam = array('m' => 'product', 'a' => 'history');
    	$arrField = array('id', 'soluong', 'dongia', 'tongtien', 'active', 'maHang', 'tensanpham', 'code', 'maHang', 'insert_at');
        $condition = array('gh_user'=>array('math' => '=', 'value' => $this->dataUser['id']));
		
        $data = $this->paging($arrParam, $arrField, $condition);
        $arrContent = $data["data"];
		$this->arrContent = array();
		$this->currPage = '';
		$this->numberPage = '';
		$this->strPaging = '';
		if (count ($arrContent) > 0) {
			foreach ($arrContent as $content) {
				$this->arrContent[] = $content;
			}
			$this->currPage = $data["currPage"];
			$this->numberPage = $data["numberPage"];
			$this->strPaging = $data["strPaging"];
		}
        
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
    * paging
    * - Array $arrParam
    * - Array $condition
    */
	public function paging($arrParam = null, $arrField = array(), $condition = array()) {
		require_once(LIB_CORE_DIR . "/Paging.class.php");
		$objPaging = new Paging();
		$ojbGioHang = new GioHang();
	    // Get total record of content menu
		$totalRecord = $ojbGioHang->getTotalData($condition);
		 // Get page current
        if (isset($_REQUEST["pageNo"])) {
        	$currentPage = $_REQUEST["pageNo"];
        }
        else {
            $currentPage = 1;
        }
		$numberRecord = 5;
        // get page number
		if (!is_null($numberRecord) && $numberRecord != 0) {
			$numberPage = ceil($totalRecord / $numberRecord);
		} else {
			$numberPage = 0;
		}
		// get start record
		$startRecord = ($currentPage - 1) * $numberRecord;

        // get array paging
		$arrPage = $objPaging->getArrPaging($currentPage, $numberPage);
		// get string page
		$strPaging = $objPaging->getStrPagingHistory($arrPage, $currentPage, $numberPage, $arrParam, true);

        // Get all content menu
        $content = $ojbGioHang->getListData($startRecord, $numberRecord, $arrField, $condition, array('insert_at' => 'DESC'));
        $no = $startRecord + 1;
		$result = array("total"=>$totalRecord,
						"data"=>$content,
						"currPage"=>$currentPage,
						"numberPage"=>$numberPage,
						"strPaging"=>$strPaging,
						"no"=>$no);

		return $result;
	}
	
	public function resultSend($gioHangA, $maHang, $phiDV) {
		$sendMai = array(array('name'=>$this->dataUser['hoten'], 'mail'=>$this->dataUser['email']));
        $subJ = "Thông tin hóa đơn mã : " . $maHang;
        $body = " + Họ và tên : " . $this->dataUser['hoten'] . "\n ".
        		"+ Địa chỉ : " . $this->dataUser['diachi'] . "\n ".
        		"+ Tỉnh/Thành phố : " . constants::$arrayCountry[$this->dataUser['tinh']] . "\n ".
        		"+ Quốc gia : Việt Nam\n ".
        		"+ Điện thoại : " . $this->dataUser['phone'] . "\n ".
        		"+ Email : " . $this->dataUser['email'] . "\n ".
        		"+ Thanh toán ngày : " . FunctionCommon::convertDate(date('Y-m-d H:i:s')) . "\n\n\n ".
        		"CHI TIẾT ĐƠN HÀNG : " . $maHang . "\n\n ";
        $tonPhiHD = 0;
        $ij = 1;
		foreach ($gioHangA as $spGH) {
			$body .= $ij." Tên sản phẩm:" . $spGH['tensanpham'] . ".  Số lượng:" . $spGH['soluong'] . "  Đơn giá:" . number_format($spGH['dongia']) . ".000 VNĐ  ==> Tổng tiền:" . number_format($spGH['tongtien']) . ".000 VNĐ \n ";
			$tonPhiHD += $spGH['tongtien'];
			$ij++;
		}				
		$body .="\n\n + Tổng tiền : " . number_format($tonPhiHD) . ".000 VNĐ\n ";
		$body .="+ Phí dịch vụ : " . $phiDV . " VNĐ\n ";
		$body .="\n\n + Tổng số tiền phải trả : " . number_format(($tonPhiHD*1000 + $phiDV)) . " VNĐ\n\n ";
			
        return FunctionCommon::sendMail($sendMai, $subJ, $body);
	}
}
?>